package cmsapi

import (
	// "net/http"
	"encoding/json"
	"strconv"

	// "time"
	// "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"

	// "github.com/jinzhu/gorm"

	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/until"
	// "oxy_server/middleware"
)

type (
	sku struct {
		ID                  bson.ObjectId `json:"_id" bson:"_id"`
		ProductID           string        `json:"productid" bson:"productid"`                     // v1 产品id
		ProductctionGroupID string        `json:"productctiongroupid" bson:"productctiongroupid"` // v2生产组id
		SkuDesc             string        `json:"skudesc" bson:"skudesc"`                         // sku 描述
		SkuCode             string        `json:"skucode" bson:"skucode"`                         //  sku 编码
		SkuCount            string        `json:"skucount" bson:"skucount"`                       // 下单数
		ActualInbound       string        `json:"actualinbound" bson:"actualinbound"`             // 实际入库数
		IsEdiet             bool          `json:"isedit" bson:"isedit"`                           // 是否可编辑
		TotalCount          int           `json:"totalcount" bson:"totalcount"`                   // 当前颜色的计划下单总数
		Percent             float64       `json:"percent" bson:"percent"`                         // 配比
		PlanCount           int           `json:"plancount" bson:"plancount"`                     // 配比
	}
	insertsku struct {
		ProductID           string  `json:"productid" bson:"productid"`
		ProductctionGroupID string  `json:"productctiongroupid" bson:"productctiongroupid"`
		SkuDesc             string  `json:"skudesc" bson:"skudesc"`
		SkuCode             string  `json:"skucode" bson:"skucode"`
		SkuCount            string  `json:"skucount" bson:"skucount"`
		ActualInbound       string  `json:"actualinbound" bson:"actualinbound"`
		IsEdiet             bool    `json:"isedit" bson:"isedit"`
		TotalCount          int     `json:"totalcount" bson:"totalcount"` // 当前颜色的计划下单总数
		Percent             float64 `json:"percent" bson:"percent"`       // 配比
		PlanCount           int     `json:"plancount" bson:"plancount"`   // 配比
	}
	Updatesku struct {
		OldSkuCode string `json:"oldskucode" bson:"skucode"`
		NewSkuCode string `json:"newskucode" bson:"skucode"`
	}
	UpdateBrand struct {
		Id    string `json:"id" bson:"id"`
		Brand string `json:"brand" bson:"brand"`
	}
)

func GetSkuListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, "_id")
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []sku{}
	query.All(&ps)

	str, err := json.Marshal(ps)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  string(str),
		"count": count,
	})

	return nil
}

func AddSkusHandler(c echo.Context) error {
	s := []insertsku{}
	if err := c.Bind(&s); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	count := 0
	var skuList []string
	for _, v := range s {
		model.DB().Document = "sku"
		err := model.DB().Insert(v)
		if err != nil {
			count++
			skuList = append(skuList, v.SkuCode)
			log.Error("批量创建skus 插入出错", err)
		}
	}
	if count > 0 {
		c.JSON(200, map[string]interface{}{
			"msg":  "error",
			"info": skuList,
		})
	} else {
		c.JSON(200, map[string]interface{}{
			"msg": "success",
		})
	}

	return nil
}

func AddSkuHandler(c echo.Context) error {
	s := &insertsku{}
	if err := c.Bind(s); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku"
	err := model.DB().Insert(s)
	if err != nil {
		log.Error("插入出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func UpdateSkuHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateSkuHandler", id)
	s := &insertsku{}
	if err := c.Bind(s); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku"
	err := model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, s)
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func UpdateSkusHandler(c echo.Context) error {
	log.Info("UpdateSkusHandler")
	s := []sku{}
	if err := c.Bind(&s); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg":  "error",
			"info": err,
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	for _, v := range s {

		model.DB().Document = "sku"
		err := model.DB().Update(bson.M{"_id": v.ID}, v)
		if err != nil {
			log.Error("更新出错", err)
			// c.JSON(404, map[string]interface{}{
			// 	"msg": "error",
			// })
			// return err
		}
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func DelSkuHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelSkuHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku"
	err := model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("删除出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

// 更新sku列表 skucode
func UpdateSkuCode(c echo.Context) error {
	log.Info("Update sku SkuCode")
	o := []Updatesku{}
	if err := c.Bind(&o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	for _, v := range o {
		model.DB().Document = "sku"
		err := model.DB().Update(bson.M{"skucode": v.OldSkuCode}, bson.M{"$set": bson.M{"skucode": v.NewSkuCode}})
		if err != nil {
			log.Error("更新sku出错 old:", v.OldSkuCode, "new:", v.NewSkuCode, err)
		}
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})
	return nil
}

func GetSkuListAnalyseHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "sku"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, "_id")
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []sku{}
	query.All(&ps)
	var percent float64 = 0
	var plancount int = 0
	for _, v := range ps {
		percent += v.Percent
		sum, _ := strconv.Atoi(v.SkuCount)
		plancount = plancount + sum
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
		"data": map[string]interface{}{
			"percent":   percent,
			"plancount": plancount,
		},
		"count": count,
	})

	return nil
}
